package com.fzu.geometa.gateway.filter;

import com.fzu.geometa.gateway.utils.JwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Set;

@Component
public class JwtAuthenticationFilter implements GlobalFilter, Ordered {
    private static final String COOKIE_TOKEN_KEY = "token";

    String TOKEN_PREFIX = "Bearer";         // Token前缀
    String HEADER_STRING = "Authorization"; // 存放Token的Header Key

    private static final String LOGIN_PAGE_URL = "/metadata/login.html";

    //白名单
    private static List<String> whitelist = null;

    static {
        //加载白名单
        try (
                InputStream resourceAsStream = JwtAuthenticationFilter.class.getResourceAsStream("/conf/whitelist.properties");
        ) {
            Properties properties = new Properties();
            properties.load(resourceAsStream);
            Set<String> strings = properties.stringPropertyNames();
            whitelist = new ArrayList<>(strings);

        } catch (Exception e) {
            //log.error("加载/security-whitelist.properties出错:{}",e.getMessage());
            e.printStackTrace();
        }
    }


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //请求的url
        String requestUrl = exchange.getRequest().getPath().value();
        AntPathMatcher pathMatcher = new AntPathMatcher();
        //白名单放行
        for (String url : whitelist) {
            if (pathMatcher.match(url, requestUrl)) {
                return chain.filter(exchange);
            }
        }

        MultiValueMap<String, HttpCookie> cookies = exchange.getRequest().getCookies();
        List<HttpCookie> tokenCookie = cookies.get(COOKIE_TOKEN_KEY);
        if (tokenCookie != null && tokenCookie.size() > 0) {
            String token = tokenCookie.get(0).getValue();
            // 验证 token 合法性
            if (JwtUtil.validateToken(token)) {

                ServerHttpRequest modifiedRequest = exchange.getRequest().mutate()
                        .headers(headers ->  headers.add(HEADER_STRING,TOKEN_PREFIX + token))
                        .build();
                ServerWebExchange modifiedExchange = exchange.mutate().request(modifiedRequest).build();
                return chain.filter(modifiedExchange);
            }
        }
        return redirectToLoginPage(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }

    private Mono<Void> redirectToLoginPage(ServerWebExchange exchange) {
        URI loginUri = exchange.getRequest().getURI().resolve(LOGIN_PAGE_URL);
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.FOUND);
        response.getHeaders().setLocation(loginUri);
        return response.setComplete();
    }
}
